﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using SMS.RoamSMPP.Smpp;
using SMS.RoamSMPP.SmppPdu;
using SMS.RoamSMPP.Library;
using WorkThreading;

namespace SMS.Gateway.Libs
{
    public class MsgOutWorkItem : WorkItem
    {
        // Fields
        private int _contentType;
        private string _messageInfo;
        private int _msgOutId;
        private string _serviceId;
        private string _userId;
        private Gateway frmGateway = null;
        private SmppSubmitSmReq.BodyPdu ReqSubmit_Sm = new SmppSubmitSmReq.BodyPdu();
        private SmppSubmitSmRes ResSubmit_Sm;
        private static Dictionary<string, string> _servDic;

        // Methods
        static MsgOutWorkItem()
        {
            _servDic = new Dictionary<string, string>();
            _servDic.Add("8078", "80");
            _servDic.Add("8178", "81");
            _servDic.Add("8278", "82");
            _servDic.Add("8378", "83");
            _servDic.Add("8478", "84");
            _servDic.Add("8578", "85");
            _servDic.Add("8678", "86");
            _servDic.Add("8778", "87");
        }

        public MsgOutWorkItem(int MsgOutID, string UserID, string ServiceID, string MessageInfo, int ContentType, Gateway frm)
        {
            this._msgOutId = MsgOutID;
            this._userId = UserID;
            this._serviceId = ServiceID;
            this._messageInfo = MessageInfo;
            this._contentType = ContentType;

            this.ReqSubmit_Sm.SourceAddress = this._serviceId;
            this.ReqSubmit_Sm.DestinationAddress = this._userId;
            this.ReqSubmit_Sm.SourceAddressTon = 1;
            this.ReqSubmit_Sm.SourceAddressNpi = 1;
            this.ReqSubmit_Sm.DestinationAddressTon = 1;
            this.ReqSubmit_Sm.DestinationAddressNpi = 1;
            this.ReqSubmit_Sm.RegisteredDelivery = new BitBuilder(1);

            this.frmGateway = frm;
        }

        public override void Perform()
        {
            if (!this.frmGateway.SmppClient.Connected)
            {
                this.UpdateStatus(2, "");
                throw new Exception("Cannot connect to SMSC");
            }

            if (this._serviceId.Length > 3)
                this._serviceId = this._serviceId.Substring(this.ServiceID.Length - 4);

            if (!_servDic.ContainsKey(_serviceId))
                throw new Exception(" Invalid ServiceID=" + this._serviceId);

            try
            {
                switch (this.ContentType)
                {
                    case 0:
                        this.SendTextMsg();
                        goto Label_01AA;

                    case 1:
                        this.SendRingMsg();
                        goto Label_01AA;

                    case 2:
                        this.SendLogoMsg();
                        goto Label_01AA;

                    case 4:
                        this.SendPicMsg();
                        goto Label_01AA;

                    case 8:
                        if (this._messageInfo.ToLower().IndexOf(":http://") == -1)
                        {
                            this.UpdateStatus(3, "");
                            throw new Exception("MsgOutID = " + this._msgOutId.ToString() + " Wrong format Wappush");
                        }
                        this.SendPushMsg();
                        goto Label_01AA;

                    case 98:
                        this.SendSetupType();
                        goto Label_01AA;

                    default:
                        this.UpdateStatus(3, "");
                        throw new Exception("Wrong MsgOutID = " + this._msgOutId.ToString() + " Content Type");
                }
            Label_01AA:
                if (this.ResSubmit_Sm.Header.CommandStatus == 0)
                {
                    this.UpdateStatus(9, this.ResSubmit_Sm.Body.MessageId);
                    if (ConfigApp.bLogMsgOut)
                    {
                        this.frmGateway.WriteLog("Send SMS from " + this._serviceId.ToString() + " to " + this._userId + " Content:" + this._messageInfo + " - MessageId=" + this.ResSubmit_Sm.Body.MessageId);
                    }
                }
                else
                {
                    this.UpdateStatus(0, "");
                    if (ConfigApp.bLogMsgOut)
                    {
                        this.frmGateway.WriteLog(string.Concat(new object[] { "Sending error SMS from ", this._serviceId.ToString(), " to ", this._userId, " Content:", this._messageInfo, " - CommandStatus=", this.ResSubmit_Sm.Header.CommandStatus }));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void SendLogoMsg()
        {
            string str2;
            string str = "06050415820000";
            if ((this._userId.Substring(0, 4) == "8490") || (this._userId.Substring(0, 4) == "8493") || (this._userId.Substring(0, 5) == "84120") || (this._userId.Substring(0, 5) == "84121") || (this._userId.Substring(0, 5) == "84122") || (this._userId.Substring(0, 5) == "84126") || (this._userId.Substring(0, 5) == "84128"))
            {
                str2 = "54F210";
            }
            else
            {
                str2 = "54F220";
            }
            byte[] buffer = Utils.Hex2Bin(str + str2 + this._messageInfo);
            this.ReqSubmit_Sm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.ReqSubmit_Sm.ShortMessage.Value = buffer;
            this.ReqSubmit_Sm.EsmClass = new BitBuilder(0x40);
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void SendPicMsg()
        {
            string hex = "0B0504158A00000003010301" + this._messageInfo.Substring(0, 0xfe);
            string str2 = "0B0504158A00000003010302" + this._messageInfo.Substring(0xfe, 0xfe);
            string str3 = "0B0504158A00000003010303" + this._messageInfo.Substring(0x1fc, 0x12);
            byte[] buffer = Utils.Hex2Bin(hex);
            byte[] buffer2 = Utils.Hex2Bin(str2);
            byte[] buffer3 = Utils.Hex2Bin(str3);
            this.ReqSubmit_Sm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.ReqSubmit_Sm.EsmClass = new BitBuilder(0x40);
            this.ReqSubmit_Sm.ShortMessage.Value = buffer;
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            this.ReqSubmit_Sm.ShortMessage.Value = buffer2;
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            this.ReqSubmit_Sm.ShortMessage.Value = buffer3;
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void SendSetupType()
        {
            byte[] buffer = Utils.Hex2Bin(this._messageInfo);
            this.ReqSubmit_Sm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.ReqSubmit_Sm.ShortMessage.Value = buffer;
            this.ReqSubmit_Sm.EsmClass = new BitBuilder(0x40);
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void SendPushMsg()
        {
            string str = this._messageInfo;
            string text = str.Substring(0, str.ToLower().IndexOf(":http://"));
            PushMessage message = new PushMessage(str.Substring(text.Length + 1, (str.Length - text.Length) - 1), text);
            HexDecoder decoder = new HexDecoder();
            string str4 = new string(decoder.GetChars(message.GetSMSBytes()));
            string[] strArray = Utils.SplitMessage(str4.Substring(14, str4.Length - 14));
            byte[][] bufferArray = new byte[strArray.Length][];
            if (strArray.Length == 1)
            {
                strArray[0] = "0605040B8423F0" + strArray[0];
                bufferArray[0] = Utils.Hex2Bin(strArray[0]);
            }
            else
            {
                for (int j = 0; j < strArray.Length; j++)
                {
                    string[] strArray2 = new string[] { "0B05040B8423F00003010", strArray.Length.ToString(), "0", (j + 1).ToString(), strArray[j] };
                    strArray[j] = string.Concat(strArray2);
                    bufferArray[j] = Utils.Hex2Bin(strArray[j]);
                }
            }
            this.ReqSubmit_Sm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.ReqSubmit_Sm.EsmClass = new BitBuilder(0x40);
            for (int i = 0; i < strArray.Length; i++)
            {
                this.ReqSubmit_Sm.ShortMessage.Value = bufferArray[i];
                this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            }
        }

        private void SendRingMsg()
        {
            string[] strArray = Utils.SplitMessage(this._messageInfo);
            byte[][] bufferArray = new byte[strArray.Length][];
            for (int i = 0; i < strArray.Length; i++)
            {
                string[] strArray2 = new string[] { "0B0504158115810003AA0", strArray.Length.ToString(), "0", (i + 1).ToString(), strArray[i] };
                strArray[i] = string.Concat(strArray2);
                bufferArray[i] = Utils.Hex2Bin(strArray[i]);
            }
            this.ReqSubmit_Sm.ShortMessage.DataCoding = SmppDataCoding.FromValue(0xf5);
            this.ReqSubmit_Sm.EsmClass = new BitBuilder(0x40);
            for (int j = 0; j < strArray.Length; j++)
            {
                this.ReqSubmit_Sm.ShortMessage.Value = bufferArray[j];
                this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
            }
            if (ConfigApp.bLogMsgOut)
            {
                string str2 = "";
                for (int k = 0; k < strArray.Length; k++)
                {
                    string str3 = str2;
                    string[] strArray3 = new string[] { str3, "\r\nMsg ", (k + 1).ToString(), " : ", strArray[k] };
                    str2 = string.Concat(strArray3);
                }
                if (this.ResSubmit_Sm.Header.CommandStatus == 0)
                {
                    this.frmGateway.WriteLog("Send MsgOut Ringtone success - From " + this._serviceId + " To " + this._userId + str2);
                }
                else
                {
                    this.frmGateway.WriteLog("Send MsgOut Ringtone failed - From " + this._serviceId + " To " + this._userId + str2);
                }
            }
        }

        private void SendTextMsg()
        {
            if (this._messageInfo.Length > 160)
            {
                this._messageInfo = this._messageInfo.Substring(0, 160);
            }
            this.ReqSubmit_Sm.ShortMessage.SetValue(this._messageInfo, SmppDataCoding.Default);
            this.ResSubmit_Sm = this.frmGateway.SubmitSm(new SmppSubmitSmReq(this.ReqSubmit_Sm));
        }

        private void UpdateStatus(int ResponseStatus, string MessageID)
        {
            string connStr = ConfigApp.ConnStr;
            string _servId = "";

            if (!_servDic.ContainsKey(_serviceId))
                throw new Exception("Invalid ServiceID = " + this._serviceId);

            _servId = _servDic[_serviceId];

            string cmdText = ("UPDATE MsgOut_" + _servId + " SET Status=@ResponseStatus,MessageID=@MessageID,ResponseTime=getdate() ") + " WHERE MsgOutID=@MsgOutID";
            SqlConnection cnn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(cmdText, cnn);
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@ResponseStatus", SqlDbType.TinyInt).Value = ResponseStatus;
            cmd.Parameters.Add("@MessageID", SqlDbType.VarChar, 50).Value = MessageID;
            cmd.Parameters.Add("@MsgOutID", SqlDbType.BigInt).Value = this._msgOutId;

            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
        }

        // Properties
        public int ContentType
        {
            get
            {
                return this._contentType;
            }
            set
            {
                this._contentType = value;
            }
        }

        public string MessageInfo
        {
            get
            {
                return this._messageInfo;
            }
            set
            {
                this._messageInfo = value;
            }
        }

        public int MsgOutID
        {
            get
            {
                return this._msgOutId;
            }
            set
            {
                this._msgOutId = value;
            }
        }

        public string ServiceID
        {
            get
            {
                return this._serviceId;
            }
            set
            {
                this._serviceId = value;
            }
        }

        public string UserID
        {
            get
            {
                return this._userId;
            }
            set
            {
                this._userId = value;
            }
        }
    }
}

